package ynu.edu.online_course.service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ynu.edu.online_course.entity.Comment;
import ynu.edu.online_course.mapper.CommentMapper;
import ynu.edu.online_course.service.CommentService;
import ynu.edu.online_course.service.UserService;

import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public void addComment(Comment comment) {
        System.out.println("Inserting comment: " + comment);
        commentMapper.insertComment(comment);
    }


    @Override
    public List<Comment> getCommentsByCourseId(Long courseId) {
        return commentMapper.findByCourseId(courseId);
    }

    UserService userService;
    @Override
    public boolean canUserDeleteComment(Long commentId, Long userId) {
        Long commentOwnerId = commentMapper.findUserIdByCommentId(commentId);
        boolean isAdmin = userService.isAdmin(userId);
        return isAdmin || (commentOwnerId != null && commentOwnerId.equals(userId));
    }

    @Override
    public void deleteComment(Long commentId, Long userId) {
        if (canUserDeleteComment(commentId, userId)) {
            commentMapper.deleteUserComment(commentId);
        } else {
            throw new SecurityException("你没有权限删除该评论");
        }
    }


}
